<template>
	<div :class="className" :style="{height:height,width:width}" />
</template>

<script>
	import * as echarts from 'echarts';
	require('echarts/theme/macarons') // echarts theme
	import resize from './mixins/resize'

	const animationDuration = 6000

	export default {
		mixins: [resize],
		props: {
			className: {
				type: String,
				default: 'chart'
			},
			width: {
				type: String,
				default: '100%'
			},
			height: {
				type: String,
				default: '683px'
			},
			chartData: {
				type: Array,
			}
		},
		data() {
			return {
				chart: null
			}
		},
		beforeDestroy() {
			if (!this.chart) {
				return
			}
			this.chart.dispose()
			this.chart = null
		},
		watch: {
			chartData: {
				deep: true,
				handler(val) {
					this.initChart();
				}
			}
		},
		methods: {
			initChart() {
				this.chart = echarts.init(this.$el, 'macarons');
				if (this.chartData.length > 15) {
					this.chartData = this.chartData.splice(0, 15);
				}
				// 1. 提取 yAxis 和 data
				const yAxis = this.chartData.map(item => item.projectName).reverse();
				const data = this.chartData.map(item => item.all).reverse();

				// 2. 计算百分比
				const total = data.reduce((acc, value) => acc + value, 0);
				const percentData = data.map(value => ((value / total) * 100).toFixed(2));

				// 3. 设置 echarts 图表选项
				this.chart.setOption({
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						},
						formatter: params => {
							const dataIndex = params[0].dataIndex;
							const projectName = yAxis[dataIndex];
							const percentValue = percentData[dataIndex];
							return `${projectName}: ${percentValue > 0?percentValue:0}%`;
						}
					},
					grid: {
						top: 10,
						left: '2%',
						right: '10%',
						bottom: '3%',
						containLabel: true
					},
					xAxis: {
						type: 'value',
						boundaryGap: [0, 0.01]
					},
					yAxis: {
						type: 'category',
						data: yAxis
					},
					series: [{
						type: 'bar',
						data: percentData,
						label: {
							show: true,
							position: 'right',
							formatter: params => {
								// 只显示非零的百分比
								if (params.value !== '0.00') {
									return `{a|${params.value}%}`;
								} else {
									return '';
								}
							},
							rich: {
								a: {
									color: '#333333', // 字体颜色设置为白色
									fontWeight: 'bold' // 加粗
								}
							}
						}
					}]
				});
			}
		}
	}
</script>